package cn.wolfcode.wolf2w.controller;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.JsonResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("users")
@Api(value = "用户资源",description = "用户资源控制器")
public class UserInfoController {
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ITravelService travelService;

    @GetMapping("/get")
    public Object get(String id){
        return userInfoService.get(id);
    }

    @ApiOperation(value = "检查手机号功能",notes = "检查手机号是否已经注册过")
    @GetMapping("/checkPhone")
    public Object checkPhone(String phone){
        boolean ret = userInfoService.checkPhone(phone);
        return !ret;
    }

    @ApiOperation(value = "发送短信功能",notes = "发送短信")
    @GetMapping("/sendVerifyCode")
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone);
        return JsonResult.success();
    }

    @ApiOperation(value = "注册功能",notes = "其实就是新增用户")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "手机号",name = "phone",dataType = "String",required = true),
            @ApiImplicitParam(value = "昵称",name = "nickname",dataType = "String",required = true),
            @ApiImplicitParam(value = "密码",name = "password",dataType = "String",required = true),
            @ApiImplicitParam(value = "确认密码",name = "rpassword",dataType = "String",required = true),
            @ApiImplicitParam(value = "验证码",name = "verifyCode",dataType = "String",required = true)
    })
    @ApiResponses({
            @ApiResponse(code=200,message="用户注册成功"),
            @ApiResponse(code=400,message="请求参数错误"),
            @ApiResponse(code=401,message="请先登录"),
            @ApiResponse(code=404,message="请求资源错误"),
            @ApiResponse(code=500,message="系统异常"),
            @ApiResponse(code=501,message="用户看的提示错误")
    })
    @PostMapping("/regist")
    public Object regist(String phone,String nickname,String password,String rpassword,String verifyCode){
        // 区分系统异常和和给用户看的异常
      /*  try {
            userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
            return JsonResult.success();
        } catch (LogicException e) {
            e.printStackTrace();
            return JsonResult.error(JsonResult.CODE_ERROR_PARAM,e.getMessage(),null);  // 501 用户看的异常
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.defaultError();  // 500 系统异常
        }*/

        // 抽取，进行统一异常处理，使用动态代理的方式。（类似AOP，切面）
        userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
        return JsonResult.success();
    }

    @ApiOperation(value = "登录功能",notes = "其实就是登录系统")
    @PostMapping("/login")
    public Object login(String username,String password){
        // 1、传入账户和密码，通过他们去数据库找，判断user是否为null，为null抛出异常，不为null为存在
        UserInfo user = userInfoService.userLogin(username,password);
        // 不为null，表示存在（存储在redis中，以便下一次访问的时候进行判断是否登录）
        // 2、创建令牌token
       String token = UUID.randomUUID().toString().replaceAll("-","");
        // 3、将user存储到redis中，并设置有效时间（key：token，value：user）
        userInfoRedisService.setToken(token,user);
        // 3、返回结果
        /**
         * data = {
         *   code:
         *   data:{
         *      token:
         *      user:
         *   }
         * }
         */
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",user);
        return JsonResult.success(map);
    }

    @GetMapping("/strategies/favor")
    public Object getStrategyList(String userId){
        List<String> list = strategyService.getUserStrategyFavor(userId);
        return JsonResult.success(list);
    }

    @GetMapping("/travels/favor")
    public Object getTravelFavorsList(String userId){
        List<String> list = travelService.getUserTravelFavor(userId);
        return JsonResult.success(list);
    }

    @RequireLogin
    @GetMapping("/currentUser")
    public Object currentUser(HttpServletRequest request){
        //1、从请求头中获取token
        String token = request.getHeader("token");
        // 2、用token作为key去redis中查value（user），判断user是否为空以判断是否登录
        UserInfo user = userInfoRedisService.getToken(token);
        user.setPassword(null);
        return JsonResult.success(user);
    }

    @ApiIgnore
    @RequireLogin
    @GetMapping("/currentUser1")
    public Object currentUser1(@UserParam UserInfo userInfo){
        return JsonResult.success(userInfo);
    }

    @GetMapping("/checkLogin")
    public Object checkLogin(@UserParam UserInfo userInfo){
        return JsonResult.success(userInfo);
    }

    @ApiIgnore
    @RequireLogin
    @GetMapping("/currentUser2")
    public Object currentUser2(UserInfo userInfo){
        return JsonResult.success(userInfo);
    }


    @RequireLogin
    @GetMapping("/userAccess")
    public Object userAccess(String id,@UserParam UserInfo userInfo){
        // 先判断进入窝的用户是不是自己，是:不处理，获取原本的redis中的访问数返回；不是，访问数+1，从redis中加1并重新设置到redis中，返回访问数
        Map<String, Object> map = new HashMap<>();
        if (id.equals(userInfo.getId())){
            String allAccess = userInfoRedisService.getAllAccess(id);
            String todayAccess = userInfoRedisService.getTodayAccess(id);
            map.put("allView",allAccess);
            map.put("todayView",todayAccess);
        }else {
            userInfoRedisService.allNumIncrease(id);
            userInfoRedisService.todayNumIncrease(id);
            String allAccess = userInfoRedisService.getAllAccess(id);
            String todayAccess = userInfoRedisService.getTodayAccess(id);
            map.put("allView",allAccess);
            map.put("todayView",todayAccess);
        }
        return JsonResult.success(map);
    }
}
